package com.xnfh.home.pop

import android.content.Context
import android.graphics.Color
import android.view.View
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.bigkoo.pickerview.view.TimePickerView
import com.lxj.xpopup.core.BottomPopupView
import com.lxj.xpopup.util.XPopupUtils
import com.xnfh.common.bean.CropBean
import com.xnfh.framework.ext.getDateYMD_CN
import com.xnfh.framework.log.LogUtil
import com.xnfh.framework.toast.TipsToast
import com.xnfh.home.R
import com.xnfh.home.databinding.PopEnclosureFieldSaveBinding

/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/11/20 15:06
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/11/20 15:06
 * @UpdateRemark: 更新说明
 */
class EnclosureFieldSavePop(context: Context) : BottomPopupView(context), View.OnClickListener {

    override fun getImplLayoutId(): Int {
        return R.layout.pop_enclosure_field_save
    }

    private var onFieldPopListener: OnFieldPopListener? = null
    open fun serOnFieldPopListener(onFieldPopListener: OnFieldPopListener) {
        this.onFieldPopListener = onFieldPopListener
    }

    interface OnFieldPopListener {
        fun selectCropListClick()

        fun saveFiled(fieldName: String,cropId: String,time: Long,fieldAreaFinally: Float)
    }

    lateinit var mBind: PopEnclosureFieldSaveBinding

    //选择作物pickerview
    lateinit var pickerBuilder: OptionsPickerView<CropBean>

    //选择时间pickerview
    lateinit var timePicker: TimePickerView

    //作物列表
    private var cropList = ArrayList<CropBean>()

    //作物id
    private var cropId: String? = null

    //种植时间
    private var time: Long? = null

    //地块面积（亩）用来存储原始值
    private var fieldArea: Float? = null

    //地块面积（亩）修改过后的值
    private var fieldAreaFinally: Float? = null

    override fun onCreate() {
        super.onCreate()
        mBind = PopEnclosureFieldSaveBinding.bind(popupImplView)
        LogUtil.d(mBind.toString(), tag = "EnclosureFieldSavePop")
        mBind.popEnclosureDknameButton.setOnClickListener(this)
        mBind.popEnclosureZztimeButton.setOnClickListener(this)
        mBind.popEnclosureDkJian.setOnClickListener(this)
        mBind.popEnclosureDkJia.setOnClickListener(this)
        mBind.popEnclosureCancle.setOnClickListener(this)
        mBind.popEnclosureSure.setOnClickListener(this)
        mBind.popEnclosureDknameEdit.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus && XPopupUtils.getDecorViewInvisibleHeight(hostWindow) != 0) {
                dismissOrHideSoftInput()
            }
        }

    }

    /**
     * 设置展示多少亩、地块的位置
     */
    fun setValue(fieldArea: String?, address: String?) {
        this.fieldArea = fieldArea?.toFloat()
        fieldAreaFinally = this.fieldArea
        mBind.enclosureMianji.text =  "$fieldAreaFinally${context.getString(R.string.str_mu)}"
        mBind.popEnclosureAddressValue.text = address
    }

    override fun onClick(v: View?) {
        when (v) {
            mBind.popEnclosureDknameButton -> {
                //未初始化先初始化，初始化了之后，下次点击可以直接展示
                if (!this::pickerBuilder.isInitialized) {
                    onFieldPopListener?.selectCropListClick()
                } else {
                    pickerBuilder.show()
                }
            }

            mBind.popEnclosureZztimeButton -> {
                showTimePicker()
            }

            mBind.popEnclosureDkJian -> {
                fieldAreaFinally = adjust(fieldArea, false, fieldAreaFinally)
                mBind.enclosureMianji.text =  "$fieldAreaFinally${context.getString(R.string.str_mu)}"

            }

            mBind.popEnclosureDkJia -> {
                fieldAreaFinally = adjust(fieldArea, true, fieldAreaFinally)
                mBind.enclosureMianji.text = "$fieldAreaFinally${context.getString(R.string.str_mu)}"
            }
            mBind.popEnclosureCancle ->{
                dismiss()
            }
            mBind.popEnclosureSure ->{
                if(mBind.popEnclosureDknameEdit.text.toString().isEmpty()){
                    TipsToast.showTips(com.xnfh.framework.R.string.pop_field_name)
                    return
                }
                if(cropId == null){
                    TipsToast.showTips(com.xnfh.framework.R.string.pop_filed_zw)
                    return
                }
                if(time == null){
                    TipsToast.showTips(com.xnfh.framework.R.string.str_qxz_zztime)
                    return
                }
                if(fieldAreaFinally == null){
                    TipsToast.showTips(R.string.toast_quandi)
                    return
                }
                onFieldPopListener?.saveFiled(mBind.popEnclosureDknameEdit.text.toString(),cropId!!,time!!,fieldAreaFinally!!)
            }
        }
    }

    private fun showTimePicker() {
        if (!this::timePicker.isInitialized) {
            timePicker = TimePickerBuilder(
                context
            ) { date, v ->
                time = date?.time
                mBind.popEnclosureZztimeButton.text = date?.time?.getDateYMD_CN()
            }.setDecorView(this).build()
        }
        timePicker.show()
    }


    /**
     * 设置所有作物信息
     */
    open fun setPickerData(list: List<CropBean>) {
        if (list.isEmpty()) return
        cropList.clear()
        cropList.addAll(list)
        if (!this::pickerBuilder.isInitialized) {
            pickerBuilder = OptionsPickerBuilder(
                context
            ) { options1, options2, options3, v ->
                //展示选中的作物
                mBind.popEnclosureDknameButton.text = cropList[options1].scName
                //存储作物id，保存地块的时候使用
                cropId = cropList[options1].dautoid
            }
                .setTitleText(context.getString(com.xnfh.framework.R.string.pop_filed_zw))
                .setTextColorCenter(Color.BLACK)
                .setContentTextSize(20)
                .setDecorView(this)
                .build()
        }
        pickerBuilder.setPicker(list)
        pickerBuilder.show()
    }

    /**
     * 上调1%或者下调1%，调整幅度最高不能超过5%
     * @param value 原始值
     * @param isIncrease 是否上调
     * @return
     */
    fun adjust(value: Float?, isIncrease: Boolean, valueUpdate: Float?): Float {
        if (valueUpdate == null || value == null) {
            throw Exception("方法 adjust() 抛出错误异常：valueUpdate || value 是空的")
        }
        // 进行上调或下调
        var valueUpdate = valueUpdate
        if (isIncrease) {
            valueUpdate += (value * 0.01).toFloat()
        } else {
            valueUpdate -= (value * 0.01).toFloat()
        }
        // 限制在10%的上下限内
        if (valueUpdate > value * 1.05f) {
            valueUpdate = value * 1.05f
        } else if (valueUpdate < value * 0.95f) {
            valueUpdate = value * 0.95f
        }
        // 保留两位小数，四舍五入
        valueUpdate = Math.round(valueUpdate * 100.0f) / 100.0f
        return valueUpdate
    }

}